package gamePlus.server;

import java.util.LinkedList;

import carddeck.Card;
import carddeck.Rank;
import carddeck.Suit;

public class GameRules {
	public static boolean canPlaySetOn(LinkedList<Card> cardsToPlay, Card onCard, int cardPenalty, int waitPenalty, Rank demand) {
		if(cardsToPlay.isEmpty())
			return false;
		Card firstCard = cardsToPlay.getFirst().getRealCard();
		if(!canPlayOn(firstCard, onCard, cardPenalty, waitPenalty, demand))
			return false;
		for(Card theCard:cardsToPlay)
			if(theCard!=firstCard&&!canPlayWith(theCard.getRealCard(), firstCard.getRealCard(), cardPenalty, waitPenalty))
				return false;
		return true;
	}
	
	public static boolean canPlayOn(Card tryCard, Card onCard, int cardPenalty, int waitPenalty, Rank demand) {
		Card realOnCard = onCard.getRealCard();
		Card realTryCard = tryCard.getRealCard();
		return cardsMatch(realOnCard, realTryCard, demand)&&canBePlayed(realTryCard, cardPenalty, waitPenalty, true);
	}
	
	public static boolean canPlayWith(Card tryCard, Card withCard, int cardPenalty, int waitPenalty) {
		return withCard.getRealCard().getCardRank() == tryCard.getRealCard().getCardRank()&&canBePlayed(tryCard.getRealCard(), cardPenalty, waitPenalty, false);
	}
	
	private static boolean canBePlayed(Card theCard, int cardPenalty, int waitPenalty, boolean bFirst) {
		if (cardPenalty > 0)
			if (theCard.getCardRank() == Rank.TWO
					|| theCard.getCardRank() == Rank.THREE
					|| theCard.getCardRank() == Rank.KING
					&& (theCard.getCardSuit() == Suit.HEARTS 
					|| theCard.getCardSuit() == Suit.SPADES)
					|| theCard.getCardRank() == Rank.QUEEN
					&& theCard.getCardSuit() == Suit.SPADES
					|| theCard.getCardRank() == Rank.QUEEN
					&& !bFirst)
				return true;
			else
				return false;
		else if (waitPenalty > 0)
			if (theCard.getCardRank() == Rank.FOUR
					|| theCard.getCardRank() == Rank.QUEEN
					&& theCard.getCardSuit() == Suit.SPADES
					|| theCard.getCardRank() == Rank.QUEEN
					&& !bFirst)
				return true;
			else
				return false;
		else
			return true;
	}
	
	private static boolean cardsMatch(Card card1, Card card2, Rank demand) {
		if (demand != null)
			if (demand != card2.getCardRank()
				&& card2.getCardRank() != Rank.JACK
				&& card2.getCardRank() != Rank.QUEEN)
				return false;
			else if (card2.getCardRank() == Rank.JACK && card1.getCardSuit() != card2.getCardSuit()&& card1.getCardRank()!=Rank.QUEEN&&card1.getCardRank()!=Rank.JACK)
				return false;
			else
				return true;
		else if (card1.getCardSuit() == card2.getCardSuit())
			return true;
		else if (card1.getCardRank() == card2.getCardRank())
			return true;
		else if (card1.getCardRank() == Rank.QUEEN
				|| card2.getCardRank() == Rank.QUEEN)
			return true;
		else
			return false;
	}
}
